//
//  SHAliPayManager.m
//  SHWeChat
//
//  Created by 索晓晓 on 2021/10/28.
//

#import "SHAliPayManager.h"
#import <AlipaySDK/AlipaySDK.h>

@interface SHAliPayManager()

@property (nonatomic , strong) NSString *scheme;

@property (nonatomic , strong) void(^payComplateBlock)(NSDictionary *info);

@end

@implementation SHAliPayManager

+ (void)regisAliPayScheme:(NSString *)scheme {
    [SHAliPayManager sharedInstance].scheme = scheme;
}

+ (instancetype)sharedInstance {
    static dispatch_once_t onceToken;
    static SHAliPayManager *instance = nil;
    dispatch_once(&onceToken,^{
        instance = [[SHAliPayManager alloc] init];
    });
    return instance;
}

/// 支付宝支付
/// @param payInfo 支付需要用到的数据
/// @param complate 完成后的回调
+ (void)payInfo:(NSString *)payInfo
       complate:(void(^)(NSDictionary *dict))complate {
    
    [SHAliPayManager sharedInstance].payComplateBlock = complate;
    
    // NOTE: 调用支付结果开始支付
    [[AlipaySDK defaultService] payOrder:payInfo fromScheme:[SHAliPayManager sharedInstance].scheme ?: @"" callback:^(NSDictionary *resultDic) {
        NSLog(@"支付宝支付回调:reslut = %@",resultDic);
        [[SHAliPayManager sharedInstance] handlePayResult:resultDic];
    }];
}

+ (BOOL)openURL:(NSURL*)url {
    
    if ([url.host isEqualToString:@"safepay"]) {
        //跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"支付宝支付回调:result = %@",resultDic);
            [[SHAliPayManager sharedInstance] handlePayResult:resultDic];
        }];
        return YES;
    }
    
    return false;
}

- (void)handlePayResult:(NSDictionary *)result {
    
    NSInteger resultCode = [result[@"resultStatus"] integerValue];
    NSMutableDictionary *callbackParams = [NSMutableDictionary dictionary];
    
    if (resultCode == 9000 || resultCode == 8000 || resultCode == 6004) {
        [callbackParams setObject:@(true) forKey:@"isSuccess"];
        [callbackParams setObject:@"支付成功" forKey:@"message"];
    } else {
        [callbackParams setObject:@(false) forKey:@"isSuccess"];
        
        [callbackParams setObject:@"订单支付失败" forKey:@"message"];

        if (resultCode == 4000) {
            [callbackParams setObject:@"订单支付失败" forKey:@"message"];
        }
        if (resultCode == 5000) {
            [callbackParams setObject:@"重复请求" forKey:@"message"];
        }
        if (resultCode == 6001) {
            [callbackParams setObject:@"取消支付" forKey:@"message"];
        }
        if (resultCode == 6002) {
            [callbackParams setObject:@"网络连接出错" forKey:@"message"];
        }
    }
    
//    9000    订单支付成功
//    8000    正在处理中，支付结果未知（有可能已经支付成功），请查询商户订单列表中订单的支付状态
//    4000    订单支付失败
//    5000    重复请求
//    6001    用户中途取消
//    6002    网络连接出错
//    6004    支付结果未知（有可能已经支付成功），请查询商户订单列表中订单的支付状态
//    其它    其它支付错误
    
    if(self.payComplateBlock){
        self.payComplateBlock(callbackParams);
        self.payComplateBlock = nil;
    }
}


@end
